import { h, Component } from 'preact';
import DockBar from '~/components/DockBar';
import { connect } from 'preact-redux';
import HeaderBar from '~/components/HeaderBar';
import ScrollLoading from '~/components/ScrollLoading';
import Modal from '~/components/Modal';
import Loading from '~/components/Loading';
import { myGroupsDetail, groupMembers, delGroup, delMember } from '~/api/groups';
import {authUrl, wechatInfo} from '~/config';
import classNames from 'classnames';
import history from '~/core/history';
import wechat, {share} from '~/utils/wechat';
import s from './OrganizationDetail.scss';

class OrganizationDetail extends Component {

	constructor(props){
		super(props);
		this.state = {
			list: [],
			edit: false,
			visible: false,
			isResult: false,
			delMember: false,
			delGroup: false,
			isMaster: false,
			dialogData: '',
			modalData: null,
			groupName: null,
			groupLogo: null,
			groupId: null,
			nextpage: 0,
			currentpage: 1,
			memberId: null,
			master: null,
			cookId: null,
			share: false
		};
	}

	componentWillMount() {
		this.setState({
			groupId: history.location.search.substr(4)
		});
		this.getGroupDetail(history.location.search.substr(4));
		this.getGroupMember(history.location.search.substr(4), 0, 10);
		if (this.props.user.id) {
			this.setState({
				cookId: this.props.user.id
			});
		}
	}

	componentWillReceiveProps(nextProps) {
		if (nextProps.user !== this.props.user) {
			this.setState({
				cookId: nextProps.user.id
			});
			this.getGroupDetail(history.location.search.substr(4));
		}
	}

	componentWillUnmount() {
		window.wx.ready(() => {
			share({
				title: `${this.props.user.name||null}分享了名片`,
				link: `${authUrl}?state=share_${this.props.user.id||null}`,
				imgUrl: this.props.user.headimgurl || wechatInfo.imgUrl,
				desc: '欢迎关注'
			});
		});
	}


	handleSetWxShare = () => {
		let { groupId, groupLogo, groupName } = this.state;
		window.wx.ready(() => {
			share({
				title: `您的好友${this.props.user.name || ''}邀请您加入${groupName}`,
				link: `${authUrl}?state=invite_${groupId||null}`,
				imgUrl: `${groupLogo||wechatInfo.imgUrl}`,
				desc: ''
			});
		});
	}

	getGroupDetail = (param) => {
		Loading.show();
		myGroupsDetail(param).then(res => {
			this.setState({
				groupName: res.groupName,
				groupLogo: res.groupLogo,
				master: res.masterId === this.state.cookId ? true : false
			});
			this.handleSetWxShare();
			Loading.hide();
		}).catch(err => {
			this.showDialog({
				dialogTitle: '对不起',
				dialogContent: err.message ? err.message : '系统繁忙, 请稍后重试！'
			});
			Loading.hide();
		});
	}

	getGroupMember = (groupid, page, size) => {
		Loading.show();
		groupMembers(groupid, page, size).then(res => {
			if (res.length >= 1) {
				for (let i=0; i < res.length; i++) {
					switch (res[i].cook.jobTitle) {
						case '0':
							res[i].cook.jobTitle = '水台';
							break;
						case '1':
							res[i].cook.jobTitle = '配菜';
							break;
						case '2':
							res[i].cook.jobTitle = '打荷';
							break;
						case '3':
							res[i].cook.jobTitle = '砧板';
							break;
						case '4':
							res[i].cook.jobTitle = '上杂';
							break;
						case '5':
							res[i].cook.jobTitle = '油鸡';
							break;
						case '6':
							res[i].cook.jobTitle = '尾锅';
							break;
						case '7':
							res[i].cook.jobTitle = '五锅';
							break;
						case '8':
							res[i].cook.jobTitle = '四锅';
							break;
						case '9':
							res[i].cook.jobTitle = '三锅';
							break;
						case '10':
							res[i].cook.jobTitle = '二锅';
							break;
						case '11':
							res[i].cook.jobTitle = '头锅';
							break;
						case '12':
							res[i].cook.jobTitle = '总厨';
							break;
						case '13':
							res[i].cook.jobTitle = '顾问';
							break;
						case '14':
							res[i].cook.jobTitle = '其他';
							break;
					}
				}
				this.setState({
					list: this.state.list.concat(res),
					nextpage: this.state.nextpage + 1,
					isMaster: res[0].isMaster
				});
			}
			Loading.hide();
		}).catch(err => {
			this.showDialog({
				dialogTitle: '对不起',
				dialogContent: err.message ? err.message : '系统繁忙, 请稍后重试！'
			});
			Loading.hide();
		});
	}

	handleAction = () => new Promise((resolve) => {
		let {groupId, nextpage} = this.state;
		this.getGroupMember(history.location.search.substr(4), nextpage, 10);
		resolve();
	});

	handleEdit = () => {
		this.setState({edit: true});
	}

	handleEndEdit = () => {
		this.setState({edit: false});
	}

	// 解散帮派
	handleDelGroup = () => {
		this.setState({
			isResult: true,
			delGroup: true,
			modalData: '您确定要解散帮派吗？'
		});
	}

	// 删除群成员
	handleDelMember = (data) => () => {
		this.setState({
			isResult: true,
			delMember: true,
			modalData: '您确定要删除此成员吗？',
			memberId: data
		});
	}

	handerConfirm = () => {
		let { groupId, memberId } = this.state;
		if (this.state.delMember) {
			this.setState({
				isResult: false,
				delMember: false
			});
			Loading.show();
			delMember(memberId).then(res => {
				this.setState({
					nextpage: 0,
					list: []
				});
				this.getGroupMember(history.location.search.substr(4), 0, 10);
				this.showDialog({
					dialogTitle: '温馨提示',
					dialogContent: '已成功删除帮派成员！'
				});
				Loading.hide();
			}).catch(err => {
				this.showDialog({
					dialogTitle: '对不起',
					dialogContent: err.message ? err.message : '系统繁忙, 请稍后重试！'
				});
				Loading.hide();
			});
		}
		if (this.state.delGroup) {
			this.setState({
				isResult: false,
				delGroup: false
			});
			Loading.show();
			delGroup(groupId).then(res => {
				this.setState({
					list: [],
					isMaster: false
				});
				history.push(decodeURIComponent(`/organization`));
				// this.showDialog({
				// 	dialogTitle: '温馨提示',
				// 	dialogContent: '已成功解散帮派！'
				// });
				Loading.hide();
			}).catch(err => {
				this.showDialog({
					dialogTitle: '对不起',
					dialogContent: err.message ? err.message : '系统繁忙, 请稍后重试！'
				});
				Loading.hide();
			});
		}
	}

	showDialog = (dialogData) => {
		this.setState(
			{
				visible: true,
				dialogData
			}
    );
	}

	// 关闭提示弹窗
	handerCloseDialog = () => {
		this.setState({
			visible: false,
			isResult: false
		});
	}

	handleInvitation = () => {
		this.setState({
			share: true
		});
		// let { groupId } = this.state;
		// history.push(`/invitation?id=${groupId}`);
	}

	handleHideShare = () => {
		this.setState({
			share: false
		});
	}

	handleCard = (id) => () => {
		history.push(`/card?cookId=${id}`);
	}

	render() {
		console.log('s', s);
		const { list, isMaster, modalData, groupName, master } = this.state;
		return (
			<div className={s.root}>
				<HeaderBar
					setTitle={groupName}
					goBack="/organization"
				>
					{master ?
						<div>
							{
								!this.state.edit ?
								<span className={classNames('icon-bj', 'white', s.edite)} onClick={this.handleEdit}/> :
								<span className={classNames('icon-yes', 'white', s.edite)} onClick={this.handleEndEdit}/>
							}
						</div> : null
					}
				</HeaderBar>
				<div className={s.listwarp}>
					<ScrollLoading
						handleAction={this.handleAction}
						totalsize={10000}
						currentpage={this.state.currentpage}
						pagesize={10}
						backToTop
						setId={'lalala'}
					>
						<ul className={`${s.list} nls`} >
							{
								list.map((item, i) => (
									<li className="clearfix" key={i}>
										<div className="w2-5 fl" onClick={this.handleCard(item.cook.id)}>
											<img src={item.cook.headimgurl} alt=""/>
										</div>
										<div className="w7-5" onClick={this.handleCard(item.cook.id)}>
											<h3 className="txt_cut font">{item.cook.name}</h3>
											<p className="txt_cut gray font-small">
												{item.cook.jobTitle}
											</p>
										</div>
										{!this.state.edit ? <a href={`tel:${item.cook.phone}`} className={s.tel}>
											<span className={classNames('icon-tel')} />
										</a> : null}
										{this.state.edit && !item.isMaster && master ? <span onClick={this.handleDelMember(item.id)}>
											<i className={classNames('icon-close', s.del)} />
										</span> : null}
									</li>
								))
							}
						</ul>
					</ScrollLoading>
				</div>
				<div className={`clearfix pa ww ${s.bottom}`}>
						<div className="mgl1 w4 al-c btn fl" onClick={this.handleInvitation} >邀请好友</div>
						{
							master ?
							<div className="mgr1 w4 al-c btnb fr" onClick={this.handleDelGroup}>解散帮派</div> :
							<div className="mgr1 w4 al-c btnb fr" onClick={this.handleDelGroup}>退出帮派</div>
						}
					</div>
				<Modal
					contentLabel="Modal"
					isOpen={this.state.isResult}
					onRequestClose={this.handleHideCard}
					shouldCloseOnOverlayClick={true}
				>
					<div className="pd1 clearfix">
						<h3 className={`al-c pdt1 orange-dark pdb1 font-bigger`}>温馨提示</h3>
						<p className="pdt1 pdb2 al-c">{modalData}</p>
						<div
							onClick={this.handerConfirm}
							className="fl w4-8 al-c btn"
						>确定</div>
						<div
							onClick={this.handerCloseDialog}
							className="fr w4-8 btnb"
						>取消</div>
					</div>
				</Modal>
				<Modal
					contentLabel="Modal"
					isOpen={this.state.visible}
					onRequestClose={this.handleHideCard}
					shouldCloseOnOverlayClick={true}
				>
				<div className="pd1 clearfix">
					<h3 className={`al-c pdt1 orange-dark font-bigger`}>{this.state.dialogData.dialogTitle}</h3>
					<p className="pdt1 pdb2 al-c">{this.state.dialogData.dialogContent}</p>
					<div
						onClick={this.handerCloseDialog}
						className="center w6 al-c btn"
					>确定</div>
				</div>
				</Modal>
				{
					this.state.share ? <div className={s.over} onClick={this.handleHideShare}><span><img src={require('./qfx.png')} alt=""/></span></div> : null
				}
			</div>
		);
	}
}


function mapStateToProps(state) {
	return {
		user: state.user
	};
}

export default connect(mapStateToProps)(OrganizationDetail);
